package com.example.minzhengtong.base

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.SystemClock
import android.text.TextUtils
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import androidx.annotation.CallSuper
import androidx.appcompat.app.ActionBar
import androidx.appcompat.app.AppCompatActivity
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.fragment.app.FragmentActivity
import com.example.minzhengtong.Const
import com.example.minzhengtong.R
import com.example.minzhengtong.data.UserBean
import com.example.minzhengtong.utils.SpUtil
import com.example.minzhengtong.utils.UIUtils
import com.example.minzhengtong.widget.WaitDialog
import com.gyf.immersionbar.ImmersionBar
import com.kaopiz.kprogresshud.KProgressHUD
import com.trello.rxlifecycle2.LifecycleProvider
import com.trello.rxlifecycle2.LifecycleTransformer
import com.trello.rxlifecycle2.RxLifecycle
import com.trello.rxlifecycle2.android.ActivityEvent
import com.trello.rxlifecycle2.android.RxLifecycleAndroid
import io.reactivex.Observable
import io.reactivex.subjects.BehaviorSubject
import kotlinx.android.synthetic.main.activity_base.*

abstract class BaseA : AppCompatActivity(), View.OnClickListener, LifecycleProvider<ActivityEvent> {

    /**
     * 上下文context
     */
    var baseContext: BaseA = this


    /**
     * 开始请求
     */
    open fun ReGetData() {

    }

    val userBean by lazy {
        SpUtil.getInstance().getObject(Const.USER_BEAN) as UserBean?
    }

    /**
     * 是否使用 EventBus
     */
    open fun useEventBus(): Boolean = true

    /**
     * 是否需要显示 TipView
     */
    open fun enableNetworkTip(): Boolean = true

    /**
     * 无网状态—>有网状态 的自动重连操作，子类可重写该方法
     */
    open fun doReConnected() {
        ReGetData()
    }


    var mImmersionBar: ImmersionBar? = null
    private var imm: InputMethodManager? = null

    /**
     * 分页加载页数
     */
    var pageNum = 1

    val TAG = javaClass.simpleName

    @CallSuper
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        super.setContentView(R.layout.activity_base)
        baseContext = this@BaseA
        ImmersionBar.with(this).navigationBarColor(R.color.white).init()
//        loadingDialog = KProgressHUD.create(this).setStyle(KProgressHUD.Style.SPIN_INDETERMINATE).setCancellable(false).setAnimationSpeed(2).setDimAmount(0.5f)
        initView()

    }

    private fun initView() {
        initToolBar()
        initImmerBar()
    }

    open fun requestSuccess(json : String){

    }

    private var mWaitDialog: WaitDialog? = null

    fun showDialog(
        isCancle: Boolean = true,
        strMsg: String? = "加载中..."
    ) {
        if (mWaitDialog == null) {
            mWaitDialog = WaitDialog.setDialog(
                baseContext,
                if (TextUtils.isEmpty(strMsg)) "加载中..." else strMsg,
                null
            )
        }
        mWaitDialog?.setCancelable(isCancle)
        mWaitDialog?.show()
    }

    fun hideDialog() {
        if (mWaitDialog != null && mWaitDialog?.isShowing()!!) {

            /**
             * 总感觉这个网络框架  加载框 结束的早了
             * 为了避免 弹框结束 到页面显示成功的 真空期
             * 暂时采用 延时取消的方式处理
             */
            Handler().postDelayed({ mWaitDialog?.dismiss() }, (200 * 1).toLong())
        }
    }

    /**
     *  初始化 状态栏设置
     *  isdark  true  设置状态栏 字体黑色  false  白色
     */
    public fun initImmerBar(isDark: Boolean = true, layoutId: Int = 0) {

        mImmersionBar = ImmersionBar.with(this)
        if (layoutId == 0) mImmersionBar?.titleBar(toolbar) else mImmersionBar?.titleBar(layoutId)
        mImmersionBar?.statusBarDarkFont(isDark, 0.2f)?.init()
    }

    fun initImmKeybord() {
        mImmersionBar?.keyboardEnable(true)?.init()
    }

    override fun setContentView(view: View) {
        val ivLeftLayoutParams: ConstraintLayout.LayoutParams = ConstraintLayout.LayoutParams(-1, 0)
        ivLeftLayoutParams.topToBottom = R.id.lay_appbar
        ivLeftLayoutParams.leftToLeft = R.id.lay_root_base
        ivLeftLayoutParams.bottomToBottom = R.id.lay_root_base
        view.layoutParams = ivLeftLayoutParams
        lay_root_base.addView(view)
    }

    override fun setContentView(layoutId: Int) {
        setContentView(View.inflate(this, layoutId, null))
    }

    override fun onClick(v: View?) {}

    private fun initToolBar() {
        setSupportActionBar(toolbar)
        val actionBar = supportActionBar
        if (actionBar != null) actionBar.displayOptions = ActionBar.DISPLAY_SHOW_CUSTOM
    }

    /**
     * 设置标题栏是否显示
     */
    fun setToolBarVisiabale(isShow: Boolean) {
        lay_appbar?.visibility = if (isShow) View.VISIBLE else View.GONE
    }

    /**
     * strTitle 标题
     * strRight1  右侧按钮
     */
    fun initTitle(strTitle: String?, strRight1: String? = "") {
        tv_base_title.text = strTitle
        if (!TextUtils.isEmpty(strRight1)) {
            tv_base_right.visibility = View.VISIBLE
            tv_base_right.setText(strRight1)
        } else tv_base_right.visibility = View.GONE
    }




    /**
     * 无网状态下的连接网络提示
     */
    open fun ShowTopAlaret() {

    }


    /**
     * 扩展 吐司
     */
    fun showToast(strMsg: String?) {
        if (strMsg.isNullOrBlank()) return
        UIUtils.showCenterToast(strMsg)
    }


    private var mActivityJumpTag: String? = null
    private var mActivityJumpTime: Long = 0

    /**
     * 检查当前 Activity 是否重复跳转了，不需要检查则重写此方法并返回 true 即可
     *
     * @param intent 用于跳转的 Intent 对象
     * @return 检查通过返回true, 检查不通过返回false
     */
    protected fun startActivitySelfCheck(intent: Intent): Boolean {
        // 默认检查通过
        var result = true
        // 标记对象
        val tag: String?
        if (intent.getComponent() != null) { // 显式跳转
            tag = intent.getComponent()!!.getClassName()
        } else if (intent.getAction() != null) { // 隐式跳转
            tag = intent.getAction()
        } else {
            return result
        }

        if (tag == mActivityJumpTag && mActivityJumpTime >= SystemClock.uptimeMillis() - 1000) {
            // 检查不通过
            result = false
        }

        // 记录启动标记和时间
        mActivityJumpTag = tag
        mActivityJumpTime = SystemClock.uptimeMillis()
        return result
    }

    override fun finish() {
        super.finish()
        hideSoftKeyBoard()
    }

    fun hideSoftKeyBoard() {
        val localView = currentFocus
        if (this.imm == null) {
            this.imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        }
        if (localView != null && this.imm != null) {
            this.imm?.hideSoftInputFromWindow(localView.windowToken, 2)
        }
    }

    /**
     * 动态隐藏软键盘
     *
     * @param context 上下文
     * @param edit    输入框
     */
    fun hideSoftInput(context: Context, edit: EditText) {
        edit.clearFocus()
        val inputmanger =
            context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        inputmanger.hideSoftInputFromWindow(edit.windowToken, 0)
    }


    @CallSuper
    override fun onDestroy() {
        lifecycleSubject.onNext(ActivityEvent.DESTROY)
        super.onDestroy()
    }

    override fun startActivityForResult(intent: Intent?, requestCode: Int) {
        if (startActivitySelfCheck(intent!!)) {
            // 查看源码得知 startActivity 最终也会调用 startActivityForResult
            super.startActivityForResult(intent, requestCode)
        }
    }

    @CallSuper
    override fun onStart() {
        super.onStart()
        lifecycleSubject.onNext(ActivityEvent.START)
    }

    @CallSuper
    override fun onResume() {

        super.onResume()
        lifecycleSubject.onNext(ActivityEvent.RESUME)
    }

    @CallSuper
    override fun onPause() {

        lifecycleSubject.onNext(ActivityEvent.PAUSE)
        super.onPause()
    }

    @CallSuper
    override fun onStop() {
        lifecycleSubject.onNext(ActivityEvent.STOP)
        super.onStop()
    }

    private val lifecycleSubject = BehaviorSubject.create<ActivityEvent>()

    override fun lifecycle(): Observable<ActivityEvent> {
        return lifecycleSubject.hide()
    }

    override fun <T : Any?> bindUntilEvent(event: ActivityEvent): LifecycleTransformer<T> {
        return RxLifecycle.bindUntilEvent(lifecycleSubject, event)
    }

    override fun <T : Any?> bindToLifecycle(): LifecycleTransformer<T> {
        return RxLifecycleAndroid.bindActivity(lifecycleSubject)
    }

    /**
     * 推送设置
     *
     * @param showtype 1 正常注册 2 退出注册
     */
    fun ExitJpush() {
        initJpushNologin()
    }

    fun initJpushNologin() {
        //设置别名（先注册）
//        JPushInterface.setAlias(baseContext, -1, "")

//        val tagSet = LinkedHashSet<String>()
//        var strTagValue = getLanguageTag()
//        tagSet.add(strTagValue)
//        JPushInterface.setTags(baseContext, 10086, tagSet)
    }


    fun shutThis(view: View){
        finish()
    }


}


